package org.example.lotterysystem.service.impl;

import org.example.lotterysystem.common.errorcode.ServiceErrorCode;
import org.example.lotterysystem.common.exception.ServiceException;
import org.example.lotterysystem.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
public class PictureServiceImpl implements PictureService {
    @Value("${pic.local-path}")
    private String loaclPath;

    @Override
    public String savePicture(MultipartFile multipartFile) {
        //创建目录
        File dir = new File(loaclPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        //创建索引
        String fileName = multipartFile.getOriginalFilename();
        assert fileName != null;
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + suffix;

        //图片保存
        try {
            multipartFile.transferTo(new File(loaclPath+"/"+fileName));
        } catch (IOException e) {
            throw new ServiceException(ServiceErrorCode.PIC_UPLOAD_ERROR);
        }

        return fileName;
    }
}
